package cn.tedu.egmvcboot.common.exception;

import cn.tedu.egmvcboot.common.result.JsonResult;
import cn.tedu.egmvcboot.common.result.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getFieldError().getDefaultMessage();
        log.error(message,e);
        return new JsonResult(Status.VALIDATED_ERROR,message);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();
        message = message.substring(message.indexOf(":")+1).trim();
        log.error(message,e);
        return new JsonResult(Status.VALIDATED_ERROR,message);
    }
}
